/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2023-12-29 14:37:11
 * @Description  : 工具类，用于格式化部分数据
 */
const moment = require('moment')
const { FILE_FORMAT } = require('@/constants')

/**
 * @description 当文件名冲突时，对文件名进行修改,加上时间戳
 * @param {string} filename 原始名称
 * @returns {string} newName 不重复的新名称
 */
module.exports.formatFilename = (filename, inc = false) => {
  if (inc) {
    return this.formatFilenameByInc
  }
  const timestamp = moment().format(FILE_FORMAT)
  // 获取文件后缀名
  const lastIndex = filename.lastIndexOf('.')
  let suffix = ''
  let before = filename
  if (lastIndex !== -1) {
    suffix = filename.substring(lastIndex)
    before = filename.substring(0, lastIndex)
  }
  const newName = before + '_' + timestamp + suffix
  return newName
}

module.exports.getFirstAndSuffix = (filename) => {
  let lastIndex = filename.lastIndexOf('.')
  let first = filename
  let suffix = ''
  if (lastIndex !== -1) {
    first = filename.substring(0, lastIndex)
    suffix = filename.substring(lastIndex)
  }

  return {
    first,
    suffix
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 根据用户输入的序列号为文件重命名
 * @param {string} filename 文件名
 * @param {number} num 序列号
 * @returns {string} 新的文件名
 */
module.exports.getNumName = (filename, num) => {
  let lastIndex = filename.lastIndexOf('.')
  let first = filename
  let suffix = ''
  if (lastIndex !== -1) {
    first = filename.substring(0, lastIndex)
    suffix = filename.substring(lastIndex)
  }
  return `${first}(${num})${suffix}`
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 字节转换为其他单位，按最大能转换的单位算起
 * @param {string} bytes 字节数
 * @returns {string} 转换字节后的最大单位
 */
module.exports.convertFromBytes = (bytes) => {
  const units = {
    B: 1n,
    KB: 1024n,
    MB: 1024n ** 2n,
    GB: 1024n ** 3n,
    TB: 1024n ** 4n
  }

  let unit = 'B'
  let value = BigInt(bytes)

  for (const key of Object.keys(units).reverse()) {
    if (value >= units[key]) {
      unit = key
      value = value / units[key]
      break
    }
  }

  return `${value.toString()}${unit}`
}
